package com.android.net.service

import android.content.Context
import android.os.Looper
import android.util.Log
import com.android.net.api.ApiService
import com.android.net.api.ApiServiceEntryPoint
import com.android.net.listener.OnAllDownloadsCompleteListener
import com.android.net.util.DownloadNotificationManager
import com.camera.base.bean.DownloadState
import com.camera.base.inerface.DownloadCallback
import dagger.hilt.android.EntryPointAccessors
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Call
import java.io.File
import java.io.RandomAccessFile

class DownloadCommonBinder: DownloadBinderImpl {
    val TAG = DownloadCommonBinder::class.java.simpleName
    var context: Context? = null
    private var downloadScope = CoroutineScope(Dispatchers.IO)
    private val downloadTasks = mutableMapOf<String, DownloadTask>()
    private val downloadQueue = mutableListOf<DownloadTask>()
    private val apiService: ApiService by lazy {
        val hiltEntryPoint = EntryPointAccessors.fromApplication(
            context!!.applicationContext,
            ApiServiceEntryPoint::class.java
        )
        hiltEntryPoint.getApiService()
    }
    private var onAllDownloadsCompleteListener: OnAllDownloadsCompleteListener? = null
    private lateinit var notificationManager: DownloadNotificationManager
    // 设置回调
    override fun setOnAllDownloadsCompleteListener(listener: OnAllDownloadsCompleteListener) {
        this.onAllDownloadsCompleteListener = listener
    }
    // 修改: startDownload 方法接受下载 URL、本地路径和回调接口作为参数
    override fun startDownload(downloadUrl: String, localPath: String, callback: DownloadCallback) {
        val fileName = File(localPath).name
        if (downloadTasks.containsKey(fileName) && downloadTasks[fileName]?.currentState != DownloadState.IDLE) {
            downloadTasks[fileName]?.callback = callback
            return
        }

        val task = DownloadTask(file = File(localPath), outputStream = null, callback = callback, downloadUrl = downloadUrl)
        task.currentState = DownloadState.WAITING // 设置初始状态为等待
        downloadTasks[fileName] = task

        // 检查当前正在下载的任务数量
        val activeDownloads = downloadTasks.count { it.value.currentState == DownloadState.DOWNLOADING }
        if (activeDownloads < 3) {
            startTask(task)
        } else {
            downloadQueue.add(task)
            Log.w(TAG, "Download queued for file: $fileName")
        }
    }

    private fun startTask(task: DownloadTask) {
        val fileName = task.file?.name ?: return
        task.currentState = DownloadState.DOWNLOADING
        task.downloadJob = downloadScope.launch {
            try {
                val downloadUrl = task.downloadUrl ?: return@launch
                val body = apiService.downloadApk(downloadUrl, "bytes=0-")

                task.contentLength = body.contentLength()

                val fileLength = task.file?.length() ?: 0
                if (task.file?.exists() == true) {
                    if (fileLength >= task.contentLength) {
                        // 文件已经完整下载，直接提示完成
                        task.currentState = DownloadState.COMPLETED
                        task.callback?.onComplete()
                        updateNotification()
                        processNextInQueue(task.file!!.name) // 处理队列中的下一个任务
                        return@launch
                    } else {
                        // 文件部分下载，继续从断点下载
                        task.totalBytesRead = fileLength
                        task.outputStream = RandomAccessFile(task.file, "rw").apply {
                            seek(fileLength) // 确保文件指针移动到正确位置
                        }
                        val rangeHeader = "bytes=${task.totalBytesRead}-"
                        val body = apiService.downloadApk(downloadUrl, rangeHeader)
                        val inputStream = body.byteStream()
                        val buffer = ByteArray(2048)
                        var bytesRead: Int

                        while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                            if (task.isPaused) {
                                task.callback?.onPause()
                                break
                            }
                            task.outputStream?.write(buffer, 0, bytesRead)
                            task.totalBytesRead += bytesRead
                            if (task.contentLength != -1L) {
                                val progress = (task.totalBytesRead * 100 / task.contentLength).toInt()
                                task.callback?.onProgress(progress)
                                updateNotification()
                            }
                        }

                        inputStream.close()
                        if (!task.isPaused) {
                            task.outputStream?.close()
                            task.currentState = DownloadState.COMPLETED
                            Log.w(TAG, "Download complete for file: $fileName")
                            task.callback?.onComplete()
                            updateNotification()
                            processNextInQueue(task.file!!.name) // 处理队列中的下一个任务
                        }
                    }
                } else {
                    // 文件不存在，从头开始下载
                    task.outputStream = RandomAccessFile(task.file, "rw")
                    val inputStream = body.byteStream()
                    val buffer = ByteArray(2048)
                    var bytesRead: Int

                    while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                        if (task.isPaused) {
                            Log.w(TAG, "Download paused for file: $fileName")
                            task.callback?.onPause()
                            break
                        }
                        task.outputStream?.write(buffer, 0, bytesRead)
                        task.totalBytesRead += bytesRead
                        if (task.contentLength != -1L) {
                            val progress = (task.totalBytesRead * 100 / task.contentLength).toInt()
                            Log.w(TAG, "Download progress for file: $fileName: $progress%")
                            task.callback?.onProgress(progress)
                            updateNotification()
                        }
                    }

                    inputStream.close()
                    if (!task.isPaused) {
                        task.outputStream?.close()
                        task.currentState = DownloadState.COMPLETED
                        Log.w(TAG, "Download complete for file: $fileName")
                        task.callback?.onComplete()
                        updateNotification()
                        processNextInQueue(task.file!!.name) // 处理队列中的下一个任务
                    }
                }
            } catch (e: Exception) {
                task.currentState = DownloadState.FAILED
                Log.w(TAG, "Error during download for file: $fileName", e)
                task.callback?.onFailure("Error during download: ${e.message}")
                updateNotification()
                processNextInQueue(task.file!!.name)
            } finally {
                task.outputStream?.close()
            }
        }
    }


    override fun resumeDownload(fileName: String) {
        val task = downloadTasks[fileName]
        if (task?.currentState == DownloadState.PAUSED) {
            task.currentState = DownloadState.DOWNLOADING
            task.downloadJob = downloadScope.launch {
                try {
                    val downloadUrl = task.downloadUrl ?: return@launch
                    val body = apiService.downloadApk(downloadUrl, "bytes=0-")

                    task.contentLength = body.contentLength()

                    val fileLength = task.file?.length() ?: 0
                    if (task.file?.exists() == true) {
                        if (fileLength >= task.contentLength) {
                            // 文件已经完整下载，直接提示完成
                            task.currentState = DownloadState.COMPLETED
                            task.callback?.onComplete()
                            updateNotification()
                            processNextInQueue(task.file!!.name) // 处理队列中的下一个任务
                            return@launch
                        } else {
                            // 文件部分下载，继续从断点下载
                            task.totalBytesRead = fileLength
                            task.outputStream = RandomAccessFile(task.file, "rw").apply {
                                seek(fileLength) // 确保文件指针移动到正确位置
                            }
                            val rangeHeader = "bytes=${task.totalBytesRead}-"
                            val body = apiService.downloadApk(downloadUrl, rangeHeader)
                            val inputStream = body.byteStream()
                            val buffer = ByteArray(2048)
                            var bytesRead: Int

                            while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                                if (task.isPaused) {
                                    task.callback?.onPause()
                                    break
                                }
                                task.outputStream?.write(buffer, 0, bytesRead)
                                task.totalBytesRead += bytesRead
                                if (task.contentLength != -1L) {
                                    val progress = (task.totalBytesRead * 100 / task.contentLength).toInt()
                                    task.callback?.onProgress(progress)
                                    updateNotification()
                                }
                            }

                            inputStream.close()
                            if (!task.isPaused) {
                                task.outputStream?.close()
                                task.currentState = DownloadState.COMPLETED
                                Log.w(TAG, "Download complete for file: $fileName")
                                task.callback?.onComplete()
                                updateNotification()
                                processNextInQueue(task.file!!.name) // 处理队列中的下一个任务
                            }
                        }
                    } else {
                        // 文件不存在，从头开始下载
                        task.outputStream = RandomAccessFile(task.file, "rw")
                        val inputStream = body.byteStream()
                        val buffer = ByteArray(2048)
                        var bytesRead: Int

                        while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                            if (task.isPaused) {
                                Log.w(TAG, "Download paused for file: $fileName")
                                task.callback?.onPause()
                                break
                            }
                            task.outputStream?.write(buffer, 0, bytesRead)
                            task.totalBytesRead += bytesRead
                            if (task.contentLength != -1L) {
                                val progress = (task.totalBytesRead * 100 / task.contentLength).toInt()
                                Log.w(TAG, "Download progress for file: $fileName: $progress%")
                                task.callback?.onProgress(progress)
                                updateNotification()
                            }
                        }

                        inputStream.close()
                        if (!task.isPaused) {
                            task.outputStream?.close()
                            task.currentState = DownloadState.COMPLETED
                            Log.w(TAG, "Download complete for file: $fileName")
                            task.callback?.onComplete()
                            updateNotification()
                            processNextInQueue(task.file!!.name) // 处理队列中的下一个任务
                        }
                    }
                } catch (e: Exception) {
                    task.currentState = DownloadState.FAILED
                    Log.w(TAG, "Error during download for file: $fileName", e)
                    task.callback?.onFailure("Error during download: ${e.message}")
                    updateNotification()
                    processNextInQueue(task.file!!.name)
                } finally {
                    task.outputStream?.close()
                }
            }
            task.callback?.onResume()
        } else {
            Log.w(TAG, "Download is not paused for file: $fileName. Current state: ${task?.currentState}")
            task?.callback?.onFailure("Download is not paused")
        }
    }


    // 在任务完成时调用检查方法
    private fun processNextInQueue(name: String) {
        downloadTasks.remove(name)
        if (downloadQueue.isNotEmpty()) {
            val nextTask = downloadQueue.removeAt(0)
            startTask(nextTask)
        } else {
            checkAllDownloadsComplete()
        }
    }

    override fun init(context: Context?) {
        this.context = context
        if (context != null) {
            notificationManager = DownloadNotificationManager(context)
        }
    }
    // 更新通知栏
    private fun updateNotification() {
        val activeTasks = downloadTasks.values.filter { it.currentState == DownloadState.DOWNLOADING }
        notificationManager.updateNotification(activeTasks, downloadTasks.size)
    }

    override fun pauseDownload(fileName: String) {
        val task = downloadTasks[fileName]
        if (task?.currentState == DownloadState.DOWNLOADING) {
            task.isPaused = true
            task.downloadJob?.cancel()
            task.currentState = DownloadState.PAUSED
            Log.w(TAG, "Download paused for file: $fileName")
            task.callback?.onPause()
        } else {
            Log.w(TAG, "Download is not in progress for file: $fileName. Current state: ${task?.currentState}")
            task?.callback?.onFailure("Download is not in progress")
        }
    }
    override fun getDownloadStateByPath(filePath: String): DownloadState? {
        val fileName = File(filePath).name
        return downloadTasks[fileName]?.currentState
    }
    override fun cancelDownload(fileName: String) {
        val task = downloadTasks[fileName]
        if (task?.currentState == DownloadState.DOWNLOADING || task?.currentState == DownloadState.PAUSED) {
            task?.isPaused = false
            task?.downloadJob?.cancel()
            task?.currentState = DownloadState.IDLE
            task?.outputStream?.close()
            task?.file?.delete()
            Log.w(TAG, "Download cancelled for file: $fileName")
            task?.callback?.onCancel()
            processNextInQueue(task.file!!.name) // 处理队列中的下一个任务
        } else {
            Log.w(TAG, "Download is not in progress or paused for file: $fileName. Current state: ${task?.currentState}")
            task?.callback?.onFailure("Download is not in progress or paused")
        }
    }
    // 检查所有下载任务是否完成
    private fun checkAllDownloadsComplete() {
        val allCompleted = downloadTasks.values.all { it.currentState == DownloadState.COMPLETED }
        if (allCompleted && downloadQueue.isEmpty()) {
            onAllDownloadsCompleteListener?.onAllDownloadsComplete()
        }
    }


    // 修改: DownloadTask 类中添加 callback 属性
    data class DownloadTask(
        var file: File?,
        var outputStream: RandomAccessFile?,
        var totalBytesRead: Long = 0,
        var contentLength: Long = -1,
        var isPaused: Boolean = false,
        var currentState: DownloadState = DownloadState.IDLE,
        var downloadJob: Job? = null,
        var callback: DownloadCallback? = null, // 添加回调接口属性
        var downloadUrl: String? = null // 添加下载URL属性
    )
}